﻿#include "speedsearch.h"
#include "ui_speedsearch.h"

#include <QCompleter>
#include <QListView>
#include <QVBoxLayout>

SpeedSearch::SpeedSearch(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::SpeedSearch)
    ,m_completer(nullptr)
{
    m_comboBox = new QComboBox(this);
    m_comboBox->setView(new QListView());
    m_comboBox->setEditable(true);
    m_comboBox->setMaxVisibleItems(30);
    connect(m_comboBox, SIGNAL(activated(QString)), this, SLOT(slotCurrentIndexChanged(QString)));
    connect(m_comboBox,&SpeedSearch::currentIndexChanged, this, &SpeedSearch::slotCurrentIndexChanged);
    QVBoxLayout *vLayout = new QVBoxLayout(this);
    vLayout->setContentsMargins(0, 0, 0, 0);
    vLayout->setSpacing(0);
    vLayout->addWidget(m_comboBox);

    this->setFixedSize(160, 24);

    ui->setupUi(this);
}

SpeedSearch::~SpeedSearch()
{
    delete ui;
}


void SpeedSearch::initData(const QStringList &strList)
{
    if (m_completer) {
        delete m_completer;
    }
    m_completer = new QCompleter(strList, this);
    m_completer->setFilterMode(Qt::MatchContains);
    m_comboBox->setCompleter(m_completer);
    m_comboBox->clear();
    m_comboBox->addItems(strList);
}

void SpeedSearch::setEditable(bool bEnabled)
{
    m_comboBox->setEditable(bEnabled);
}

void SpeedSearch::setCurrentText(const QString & sText)
{
    m_comboBox->setCurrentText(sText);
}

QString SpeedSearch::currentText()
{
    return m_comboBox->currentText();
}

void SpeedSearch::setCurrentIndex(const int & nIdx)
{
    m_comboBox->setCurrentIndex(nIdx);
}

int SpeedSearch::currentIndex()
{
    return m_comboBox->currentIndex();
}

void SpeedSearch::AddItem(const QString & sText)
{
    m_comboBox->addItem(sText);
}

QString SpeedSearch::itemText(int idx)
{
    return m_comboBox->itemText(idx);
}

void SpeedSearch::hideSubcontrol()
{
    m_comboBox->setStyleSheet("QComboBox::drop-down { subcontrol-origin: padding; width: 0px; height: 0px; image: none; }");
}

void SpeedSearch::setPlaceholderText(QString & sText)
{
    m_comboBox->insertItem(0, "");
    m_comboBox->setItemText(0, sText);
}

int SpeedSearch::Count()
{
    return m_comboBox->count();
}

void SpeedSearch::slotCurrentIndexChanged(const QString &str)
{
    qDebug() << "slotCurrentIndexChanged==>"<< str;
    //hide();
    emit currentIndexChanged(str);
}

void SpeedSearch::showEvent(QShowEvent *event)
{
    QWidget::showEvent(event);
    // m_comboBox->setCurrentText("");
    m_comboBox->setFocus();
}
